package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.Gson;
import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.activities.NewDigestActivity;
import me.shurufa.adapter.BookExcerptAdapter;
import me.shurufa.bean.Excerpt;
import me.shurufa.controller.DataController;
import me.shurufa.controller.ExcerptCommentCounterController;
import me.shurufa.model.BookDigestListResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.ExcerptListResp;
import me.shurufa.response.base.BaseResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.pulltorefresh.SrfPtrFrameLayout;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.timelineheader.HeaderDigestBarLayout;
import me.shurufa.widget.timelineheader.OnBarItemClickListener;

/**
 * 作者 : andy
 * 日期 : 16/3/9 10:31
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 书摘Fragment
 */
public class BookExcerptFragment extends BaseFragment implements View.OnClickListener, AppBarLayout.OnOffsetChangedListener {

    @Bind(R.id.recycler_view)
    SuperRecyclerView recyclerView;

    @Bind(R.id.ptr_refresh)
    SrfPtrFrameLayout ptrRefresh;

    @Bind(R.id.header_digist_bar)
    HeaderDigestBarLayout header_digist_bar;

    @Bind(R.id.appbar)
    AppBarLayout mAppBar;

    @Bind(R.id.progress)
    SpinKitView progress;

    private ArrayList<Excerpt> mDataList = new ArrayList<>();
    private BookExcerptAdapter mExcerptAdapter;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;

    private boolean changeTab = false;
    private int mWhereFrom;
    private long bookId;

    private String mBookname;
    private Handler mHandler = new Handler();
    private String mUserId;
    private int mVerticalOffset;

    private int mItemBarIndex;
    private boolean mItemBarDesc;

    // 刷新需要
    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (NetworkUtils.isNetAvailable(getActivity())) {
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                loadData(mPage);
            }
        }
    };

    public static BookExcerptFragment newInstance(long bookId, String bookname, int whereFrom, String userId) {
        BookExcerptFragment fragment = new BookExcerptFragment();
        Bundle args = new Bundle();
        args.putInt(Constants.ARG_FROM_WHERE, whereFrom);
        args.putLong(Constants.ARG_BOOK_ID, bookId);
        args.putString(Constants.ARG_BOOK_TITLE, bookname);
        args.putString(Constants.ARG_USER_ID, userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            bookId = getArguments().getLong(Constants.ARG_BOOK_ID);
            mWhereFrom = getArguments().getInt(Constants.ARG_FROM_WHERE);
            mBookname = getArguments().getString(Constants.ARG_BOOK_TITLE);
            mUserId = getArguments().getString(Constants.ARG_USER_ID);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_digest_list_new, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 加载一次
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh != null) {
                    ptrRefresh.autoRefresh(true);
                }
            }
        }, 400);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);

        // 初始化刷新
        setRefresh();

        mExcerptAdapter = new BookExcerptAdapter(getActivity(), mBookname, mDataList, mWhereFrom);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mExcerptAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.getRecyclerView().setOverScrollMode(View.OVER_SCROLL_NEVER);


        // 默认隐藏，刷新后无数据的话才显示
        recyclerView.getEmptyView().setVisibility(View.GONE);

        //setLayoutManager
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        initListener();

        if (mWhereFrom == Constants.TYPE_FRAGMENT_MYCOLLECT) {
            header_digist_bar.setVisibility(View.GONE);
        }


    }

    /**
     * 初始化监听器
     */

    private void initListener() {
        recyclerView.setOnScrollListener(mOnScrollListener);
        mAppBar.addOnOffsetChangedListener(this);

        header_digist_bar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        header_digist_bar.setOnBarItemClickListener(new OnBarItemClickListener() {
            @Override
            public void onClick(int index, boolean desc, int previousIndex) {
                changeTab = true;
                mItemBarIndex = index;
                mItemBarDesc = desc;
                refresh();
            }
        });

        // 评论点击按钮监听
        mExcerptAdapter.setOnSocialBarClickListener(new BookExcerptAdapter.OnOperateClickListener() {

            @Override
            public void onPraiseClick(boolean prePraise, Excerpt excerpt) {
                if (!prePraise) {
                    reqPraise(excerpt);
                } else {
                    reqCancelPraise(excerpt);
                }
            }

            @Override
            public void onCollectClick(boolean preCollect, Excerpt excerpt) {
                if (!preCollect) {
                    reqCollect(excerpt);
                } else {
                    reqCancelCollect(excerpt);
                }
            }
        });

    }


    /**
     * 取消收藏
     * @param excerpt 书摘
     */
    private void reqCancelCollect(final Excerpt excerpt) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", excerpt.id);
        params.addFormDataPart("item", "excerpt");

        HttpRequest.post(API.DEL_FAV, params, new HttpCallback<BaseResp>(getActivity()) {

            @Override
            public void onRespSuccess(BaseResp baseResp) {
                try {
                    excerpt.is_fav = 0;
                    mExcerptAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp baseResp) {

            }
        });
    }

    /**
     * 收藏
     * @param excerpt 书摘
     */
    private void reqCollect(final Excerpt excerpt) {

        RequestParams params = new RequestParams();
        params.addFormDataPart("id", excerpt.id);
        params.addFormDataPart("item", "excerpt");

        HttpRequest.post(API.ADD_FAV, params, new HttpCallback<BaseResp>(getActivity()) {

            @Override
            public void onRespSuccess(BaseResp baseResp) {
                try {
                    excerpt.is_fav = 1;
                    mExcerptAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp baseResp) {

            }
        });
    }

    /**
     * 取消点赞
     * @param excerpt 书摘
     */
    private void reqCancelPraise(final Excerpt excerpt) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", excerpt.id);
        params.addFormDataPart("item", "excerpt");

        HttpRequest.post(API.DEL_ZAN, params, new HttpCallback<BaseResp>(getActivity()) {
            @Override
            public void onRespSuccess(BaseResp resp) {
                try {
                    excerpt.is_zan = 0;
                    excerpt.zan_num -= 1;
                    if (excerpt.zan_num < 0) {
                        excerpt.zan_num = 0;
                    }
                    mExcerptAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp resp) {

            }
        });
    }

    /**
     * 点赞
     * @param excerpt 书摘
     */
    private void reqPraise(final Excerpt excerpt) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", excerpt.id);
        params.addFormDataPart("item", "excerpt");

        HttpRequest.post(API.ADD_ZAN, params, new HttpCallback<BaseResp>(getActivity()) {
            @Override
            public void onRespSuccess(BaseResp resp) {
                try {
                    excerpt.is_zan = 1;
                    excerpt.zan_num += 1;
                    mExcerptAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp resp) {

            }
        });

    }


    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {
        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView.getRecyclerView());
                if (state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    if (!NetworkUtils.isNetAvailable(getActivity())) {
                        RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                        return;
                    }
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(mPage);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(200);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                return mVerticalOffset == 0 && PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, ((SuperRecyclerView) view).getRecyclerView(), view1);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, BookDigestListResponse.class);
    }

//Load and Refresh


    @Override
    public void refresh() {
        super.refresh();
        if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
            ptrRefresh.refreshComplete();
        }

        // process request
        mPage = 1;
        loadData(mPage);
    }


    /**
     * 加载数据
     * @param page 页码
     */
    private void loadData(final int page) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("page", page);
        params.addFormDataPart("book_id", bookId);

        String api = API.GET_EXCERPT_LIST;
        // 如果是从我的收藏进来的
        if (mWhereFrom == Constants.TYPE_FRAGMENT_MYCOLLECT) {
            api = API.GET_FAV_EXCERPT_BY_BOOK_USER;
        } else {
            params.addFormDataPart("user_id", mUserId);
            params.addFormDataPart("order_by", getOrderByParam());

            if (Constants.TYPE_FROM_USER_CENTER_DIGEST == mWhereFrom || Constants.TYPE_FROM_USER_CENTER_COMMENT == mWhereFrom) {
                api = API.GET_EXCERPT_LIST_BY_USER;
            }
        }


        HttpRequest.post(api, params, new HttpCallback<ExcerptListResp>() {

            @Override
            public void onRespSuccess(final ExcerptListResp excerptListResp) {
                try {
                    handleResponse(excerptListResp, (page == 0 || page == 1));
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(ExcerptListResp bookListResp) {

            }

            @Override
            public void onStart() {
                super.onStart();
                try {
                    if (NetworkUtils.isNetAvailable(getActivity())) {
                        RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.Loading);
                        if (changeTab) {
                            progress.setVisibility(View.VISIBLE);
                        }
                    } else {
                        // 是上拉加载
                        if (mPage > 1) {
                            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                try {
                    progress.setVisibility(View.GONE);
                    refreshComplete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Require run in UIThread
     */
    public void refreshComplete() {
        // 是上拉加载更多
        if (mPage > 1) {
            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), hasMore ? LoadingFooter.State.Normal : LoadingFooter.State.TheEnd);
        }

        // 是下拉加载
        if (ptrRefresh != null && mPage <= 1) {
            ptrRefresh.refreshComplete();
        }
    }

    /**
     * 处理返回结果
     * 1. 去重
     * @param listResp     dataList
     * @param isPullToRefresh  boolean
     */
    private void handleResponse(ExcerptListResp listResp, boolean isPullToRefresh) {

        if (changeTab) {
            mExcerptAdapter.clear();
            mExcerptAdapter.notifyDataSetChanged();
            changeTab = false;
        }

        // 是否还有更多
        hasMore = mPage < listResp.max_page;

        // 1. 判空
        if (listResp.data == null || Utils.isNullForList(listResp.data)) {
            if (isPullToRefresh) {
                recyclerView.getEmptyView().setVisibility(View.VISIBLE);
            }
            return;
        }

        // 2. 去重
        if (!isPullToRefresh) {
            listResp.data = DataController.getValidExcerptList(mDataList, listResp.data);
        } else {
            mExcerptAdapter.clear();
            mExcerptAdapter.notifyDataSetChanged();
        }
        mExcerptAdapter.append(listResp.data);
        mPage ++;
    }


    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh != null) {
                        ptrRefresh.refreshComplete();
                    }
                }
            }, 500);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.book_img:
                Utils.showToast(R.string.my_favourite_digest);
                break;
            case R.id.left_text:
                intent = new Intent(getActivity(), NewDigestActivity.class);
                startActivity(intent);
                break;
            case R.id.right_text:
                intent = new Intent(Constants.ACTION_MAIN_SWITCH);
                intent.putExtra(Constants.EXTRA_SWITCH_INDEX, 0);
                EventBus.getDefault().post(intent);
                break;
        }
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (Constants.ACTION_BOOKSHELVES_REFRESH.equals(intent.getAction()) ||
                Constants.ACTION_ADD_DIGEST_COMPLETE.equals(intent.getAction())) {
            refresh();
        }

        // 添加了评论
        if (Constants.EVENT_SEND_COMMENT.equals(intent.getAction())) {
            int type = intent.getIntExtra(Constants.ARG_PARENT_TYPE, 0);
            if (Constants.TYPE_COMMENT_EXCERPT == type) {
                int excerptId = intent.getIntExtra(Constants.ARG_PARENT_ID, 0);
                ExcerptCommentCounterController controller = new ExcerptCommentCounterController(mExcerptAdapter, mDataList, excerptId);
                controller.handleAddCounter();
            }
        }

    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        mVerticalOffset = verticalOffset;
    }

    /**
     * 获得排序的请求参数
     * @return params
     */
    public String getOrderByParam() {

        if (null == header_digist_bar) {
            return "top";
        }
        switch (mItemBarIndex) {
            // 最赞
            case 0:
                return "top";
            // 章节
            case 1:
                return "menu";
            // 时间
            case 2:
                return mItemBarDesc ? "time_up" : "time_down";
            // 页码
            case 3:
                return mItemBarDesc ? "page_up" : "page_down";
            default:
                return "top";
        }
    }
}
